package cn.matezk.cloud.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.matezk.cloud.dao.UserDao;
import cn.matezk.cloud.model.User;
import cn.matezk.cloud.service.IUserService;
import jdk.nashorn.internal.runtime.regexp.joni.exception.InternalException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class UserService implements IUserService {
    @Autowired
    private UserDao userDao;
    @Value("${tencent.iot-app-id}")
    private String iotAppId;

    @Override
    public User select(User user) {
        User db = userDao.selectByPrimaryKey(user.getUnionId());
        if (ObjectUtil.isNull(db)) {
            user.setAppId(iotAppId);
            user.setIsSub(Boolean.FALSE);
            user.setWechatNotifyEnable(Boolean.FALSE);
            userDao.insertSelective(user);
            return user;
        }
        if (ObjectUtil.isEmpty(db.getUserId())) {
            user.setAppId(iotAppId);
            user.setUserId(user.getUserId());
            userDao.updateByPrimaryKeySelective(user);
        }
        return db;
    }

    @Override
    public int update(User user) {
        User db = userDao.selectByPrimaryKey(user.getUnionId());
        if (Boolean.TRUE.equals(user.getWechatNotifyEnable()) && Boolean.FALSE.equals(db.getIsSub())) {
            throw new InternalException("请先关注【美特连连】公众号");
        }
        return userDao.updateByPrimaryKeySelective(user);
    }
}
